package com.zb.security.listener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.authentication.event.AbstractAuthenticationEvent;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent;
import org.springframework.security.authentication.event.LoggerListener;
import org.springframework.util.ClassUtils;

/**
 * 权限认证Spring日志监听器
 * 
 * 作者: zhoubang 
 * 日期：2015年8月25日 下午5:34:08
 */
public class MyLoggerListener extends LoggerListener {

	private static final Log logger = LogFactory.getLog(LoggerListener.class);
	
	private boolean logInteractiveAuthenticationSuccessEvents = true;
	
	public void onApplicationEvent(AbstractAuthenticationEvent event) {
		if (!logInteractiveAuthenticationSuccessEvents && event instanceof InteractiveAuthenticationSuccessEvent) {
            return;
        }

        if (logger.isWarnEnabled()) {
            final StringBuilder builder = new StringBuilder();
            builder.append("身份验证  ");
            builder.append(ClassUtils.getShortName(event.getClass()));
            builder.append(": ");
            builder.append("用户名———— ");
            builder.append(event.getAuthentication().getName());
            builder.append("; details: ");
            builder.append(event.getAuthentication().getDetails());
            
            if (event instanceof AbstractAuthenticationFailureEvent) {
                builder.append("; exception: ");
                builder.append(((AbstractAuthenticationFailureEvent) event).getException().getMessage());
            }

            logger.warn(builder.toString());
        }
	}
}
